package evil.wolf.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

import evil.wolf.excute.query.ExcuteQuery;
import evil.wolf.objects.ObjectCTNhapXuat;
import evil.wolf.objects.ObjectNhapXuat;
import evil.wolf.panels.ListNhapUI;


/**
 * A panel with the title and the text of a book.
 * 
 * @author Heidi Rakels.
 */
@SuppressWarnings("serial")
public class UINhap extends JDialog{
	
	Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
	
	// Static fields.
	@SuppressWarnings("unused")
	private static final String NEWLINE = System.getProperty("line.separator");
	
	public JTextField txtsoct;
	public JTextField txtngayct;
	public JTextField txtmakh;
	public JTextField txtdg;
	public JTextField txtloaict;
	
	public JButton buttonAction;
	public JButton btnEdit;
	ListNhapUI listNhapUI;
	ObjectNhapXuat objectNhap;
	ObjectNhapXuat newObjectNhapXuat = new ObjectNhapXuat();
	MainUI mainUI;
	public String oldValue;
	
	DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
	
	public UINhap(MainUI mainUI, ListNhapUI listNhapUI, ObjectNhapXuat objectNhap) {
		super();
		this.mainUI = mainUI; 
		add(streamData());
		this.listNhapUI = listNhapUI;
		this.objectNhap = objectNhap;
//		if(listNhapUI.getAction() == null) 
//			listNhapUI.setAction(evil.wolf.action.Action.ACTION_INSERT);
		
		this.setAlwaysOnTop(true);
		setSize(360, 250);
		this.setTitle("Nhập");
		setResizable(false);
		setLocation((dim.width - getWidth())/2, (dim.height - getHeight())/2);
//		if(listNhapUI.getAction().trim() == evil.wolf.action.Action.ACTION_INSERT) {
//			buttonAction.setText(evil.wolf.action.Action.ACTION_INSERT);
//		}
//		else
//			buttonAction.setText(evil.wolf.action.Action.ACTION_UPDATE);
		
	}
	
	public JPanel streamData()
	{
		JPanel mainPanel = new JPanel();
		
		mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
		mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 10));
		
		JPanel helppanel1 = new JPanel(new BorderLayout());
		
		JPanel helppanel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
		helppanel2.setPreferredSize(new Dimension(25, 110));
		
		JPanel labelpanel = new JPanel(new GridLayout(7, 1, 0, 0));
		labelpanel.setPreferredSize(new Dimension(70, 180));
		
		JLabel stremty = new JLabel(" ");
		labelpanel.add(stremty, Component.RIGHT_ALIGNMENT);
		
		JLabel strtenh = new JLabel("số ct");
		labelpanel.add(strtenh, Component.RIGHT_ALIGNMENT);
		
		JLabel strmanh = new JLabel("ngày ct");
		labelpanel.add(strmanh, Component.RIGHT_ALIGNMENT);
				
		JLabel strdvt = new JLabel("mã kh");
		labelpanel.add(strdvt, Component.RIGHT_ALIGNMENT);
		
		JLabel strsl = new JLabel("Diễn giải");
		labelpanel.add(strsl, Component.RIGHT_ALIGNMENT);
		
		JLabel strdd = new JLabel("Loại CT");
		labelpanel.add(strdd, Component.RIGHT_ALIGNMENT);
		
		helppanel1.add(labelpanel, BorderLayout.CENTER);
		helppanel1.add(Box.createRigidArea(new Dimension(10, 10)), BorderLayout.WEST);
		helppanel1.add(helppanel2, BorderLayout.SOUTH);
		JPanel comm1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
		comm1.add(helppanel1);
		
		JPanel textpanel = new JPanel( new FlowLayout(FlowLayout.LEFT, 5, 5) );
		textpanel.setPreferredSize(new Dimension(260, 245)); 
		
		txtsoct = new JTextField(20);
		textpanel.add(txtsoct);
		
		txtngayct = new JTextField(20);
		textpanel.add(txtngayct);

		JPanel tenh_mah_panel = new JPanel( new FlowLayout(FlowLayout.LEFT, 0, 5) );
		tenh_mah_panel.setPreferredSize(new Dimension(98, 93));
		txtmakh = new JTextField(10);
		tenh_mah_panel.add(txtmakh);
		tenh_mah_panel.add(Box.createRigidArea(new Dimension(0, 10)));
		txtdg = new JTextField(10);
		tenh_mah_panel.add(txtdg);
		txtloaict = new JTextField(10);
		tenh_mah_panel.add(txtloaict);
		textpanel.add(tenh_mah_panel);

		
		comm1.add(textpanel);
		
		mainPanel.add(comm1);
		
		JPanel buttonpanel = new JPanel(new GridLayout(1, 4 , 5 , 5) );
  	
		buttonpanel.add(Box.createRigidArea(new Dimension(0, 0)));
		buttonpanel.add(Box.createRigidArea(new Dimension(0, 0)));
		buttonAction = new JButton("INSERT");
		buttonAction.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				
				if(listNhapUI.getAction().trim() == evil.wolf.action.Action.ACTION_INSERT){
					insertNhap();
				}

//============================================================================================================
				if(listNhapUI.getAction().trim() == evil.wolf.action.Action.ACTION_UPDATE) {
					updateNhap();
				}
			}
		});
		
		buttonpanel.add(buttonAction, Component.RIGHT_ALIGNMENT) ;
		
		btnEdit = new JButton("Cancel");
		final UINhap themhh;
		themhh = this;
		btnEdit.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				themhh.setVisible(false);
			}
		});
		buttonpanel.add(btnEdit, Component.RIGHT_ALIGNMENT) ;
		mainPanel.add(buttonpanel);
		
        return mainPanel;
	}

	private void insertNhap() {

		if (checkInDataExist()) {
			
			newObjectNhapXuat.setsoct(txtsoct.getText().toString().trim());
			try {
				newObjectNhapXuat .setngayct(formatter.format((Date)formatter.parse(txtngayct.getText().toString().trim())));
			} catch (ParseException e) {

				e.printStackTrace();
			}
			newObjectNhapXuat.setmakh(txtmakh.getText().toString().trim());
			newObjectNhapXuat.setdg(txtdg.getText().toString().trim());
			newObjectNhapXuat.setloaict(txtloaict.getText().toString().trim());
			
			ExcuteQuery doAction = new ExcuteQuery();
			if(doAction.insertNhap(newObjectNhapXuat)) {
			
				try{
					
					mainUI.listNhapUI.arrayLaterials.add(newObjectNhapXuat);
					mainUI.listNhapUI.dataTableNhap.revalidate();
					setVisible(false);
				}
				catch(Exception ex){
					JOptionPane.showMessageDialog(null,	ex.toString(), "ERROR", JOptionPane.INFORMATION_MESSAGE);
					ex.printStackTrace();
				}
					
				txtsoct.setText("");
				txtngayct.setText(""); 
				txtmakh.setText("");
				txtdg.setText("");
				txtloaict.setText("");
				
				ObjectCTNhapXuat objectCTNhapXuat = new ObjectCTNhapXuat();
				UICTNhapXuat uiCTNhapXuat = new UICTNhapXuat(mainUI, listNhapUI, mainUI.listCTNhapXuatUI,objectCTNhapXuat, newObjectNhapXuat);
				uiCTNhapXuat.setVisible(true);
			}
		}
	
	}
	private void updateNhap() {

		int row = listNhapUI.getSelectedRow();
		if (checkInDataExist()) {
			ObjectNhapXuat mobjectNhap = new ObjectNhapXuat();
			mobjectNhap .setsoct(txtsoct.getText().toString().trim());
			try {
				mobjectNhap .setngayct(formatter.format((Date)formatter.parse(txtngayct.getText().toString().trim())));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}					
			mobjectNhap .setmakh(txtmakh.getText().toString().trim());
			mobjectNhap .setdg(txtdg.getText().toString().trim());
			mobjectNhap .setloaict(txtloaict.getText().toString().trim());
			
			ExcuteQuery doAction = new ExcuteQuery();
			if(doAction.updateNhap(mobjectNhap, objectNhap.getsoct(), objectNhap.getmakh(), objectNhap.getloaict())) {
				
				try{
					mainUI.listNhapUI.arrayLaterials.remove(row);
					mainUI.listNhapUI.arrayLaterials.add(row, mobjectNhap);
					mainUI.listNhapUI.dataTableNhap.repaint();
					setVisible(false);
				}
				catch(Exception ex){
					JOptionPane.showMessageDialog(null,	ex.toString(), "ERROR", JOptionPane.INFORMATION_MESSAGE);
					ex.printStackTrace();
				}
			}
			
		}
	
	}
	public void setTextUI(ObjectNhapXuat objectNhap){
		txtsoct.setText(objectNhap.getsoct());
		txtngayct.setText(objectNhap.getngayct().toString());
		txtmakh.setText(objectNhap.getmakh());
		txtdg.setText(objectNhap.getdg());
		txtloaict.setText(objectNhap.getloaict());
	}
	
	private boolean checkInDataExist() {
		if((txtsoct.getText().trim() == null) || (txtngayct.getText().trim() == null) || (txtmakh.getText().trim() == null) ||  (txtdg.getText().trim() == null)  || (txtloaict.getText().trim() == null))
			return false;
		else
			return true;
	}
	
	/**
	 * Adds the styles to a styled document.
	 * 
	 * @param doc		The styled document.
	 * @param picture	A picture used in the document.
	 */
	protected void addStylesToDocument(StyledDocument doc, Icon picture) {

        Style def = StyleContext.getDefaultStyleContext().
                        getStyle(StyleContext.DEFAULT_STYLE);

        Style regular = doc.addStyle("regular", def);
        StyleConstants.setFontFamily(def, "SansSerif");

        Style style = doc.addStyle("italic", regular);
        StyleConstants.setItalic(style, true);

        style = doc.addStyle("bold", regular);
        StyleConstants.setBold(style, true);

        style = doc.addStyle("small", regular);
        StyleConstants.setFontSize(style, 10);

        style = doc.addStyle("large", regular);
        StyleConstants.setFontSize(style, 16);
        StyleConstants.setBold(style, true);
        
        style = doc.addStyle("icon", regular);
        StyleConstants.setAlignment(style, StyleConstants.ALIGN_CENTER);
        
        if (picture != null) {
            StyleConstants.setIcon(style, picture);
        }
    }
	
}
